package no.sachmuld.methodcombination.demo;

import no.sachmuld.methodcombination.api.MethodInvocation;
import org.apache.log4j.Logger;
import org.springframework.dao.DuplicateKeyException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 */
public class ExceptionMappingFilterBehaviour extends FilterBehaviour {

    private static Logger logger = Logger.getLogger(ExceptionMappingFilterBehaviour.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, MethodInvocation<Void> methodInvocation) throws IOException, ServletException {

        try {

            methodInvocation.proceed();

        } catch (DuplicateKeyException e) {
            handleException(e, response, HttpServletResponse.SC_BAD_REQUEST);
        } catch (Exception e) {
            handleException(e, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

    }

    private void handleException(Exception exception, ServletResponse servletResponse, int status) {

        ((HttpServletResponse) servletResponse).setStatus(status);
        logger.info("Status " + status + " returned for exception " + exception.getClass() + " with message " + exception.getMessage());

    }
}
